package com.test;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;

public class ImageCompressor {
    public static void main(String[] args) throws IOException {
        File inputImage = new File("e:/test/222.jpg");
        File outputImage = new File("e:/test/222-o.jpg");
        compressImage(inputImage, outputImage, 0.1f);
    }

    public static void compressImage(File inputImage, File outputImage, float quality) throws IOException {
        BufferedImage originalImage = ImageIO.read(inputImage);
        // 使用JPEGImageWriter压缩图片
        ImageIO.write(originalImage, "jpg", outputImage);
        // 设置JPEG压缩质量，质量范围是0.0f到1.0f
        float compressionQuality = quality; // 例如0.5f表示压缩到一半大小
        Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
        if (writers.hasNext()) {
            ImageWriter writer = writers.next();
            ImageWriteParam param = writer.getDefaultWriteParam();
            if (param.canWriteCompressed()) {
                param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
                param.setCompressionQuality(compressionQuality);
                writer.setOutput(ImageIO.createImageOutputStream(outputImage));
                writer.write(null, new IIOImage(originalImage, null, null), param);
            }
        }
    }
}